package com.xh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xh.mapper.UserMapper;
import com.xh.pojo.LoginInfo;
import com.xh.pojo.Result;
import com.xh.pojo.User;
import com.xh.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/*
 * @author：Zero度
 * @2020/12/10 22:57
 * 文件说明：
 * */

@Service
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 查询用户、认证用户
     * @param user
     * @return
     */
//    @Override
    public Result selectUser(User user) {

        Result result = new Result();
//        User user = userMapper.selectUser(userName);
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();

        if(!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
            try {
                subject.login(token);   // 执行登录方法，如果没有异常就说明ok了
                User currentUser = (User) subject.getPrincipal();
                LoginInfo loginInfo = new LoginInfo();
                loginInfo.setUid(currentUser.getUid());
                loginInfo.setUserName(currentUser.getUserName());
                loginInfo.setRole(currentUser.getRole());
                loginInfo.setToken((String) token.getPrincipal());
                result.setLoginInfo(loginInfo);
                result.setCode(200);
                result.setMessage("登录成功");
                return result;
            } catch (UnknownAccountException e) { // 用户名不存在
                result.setMessage("用户名不存在");
                result.setLoginInfo(null);
                result.setCode(null);
                return result;
            } catch (IncorrectCredentialsException e) {   // 密码不存在
                result.setMessage("密码错误");
                result.setLoginInfo(null);
                result.setCode(null);
                return result;
            } catch (LockedAccountException e) {  // 用户被锁定
                result.setMessage("用户被锁定");
                result.setLoginInfo(null);
                result.setCode(null);
                return result;
            }
        }else{
            return null;
        }
    }
}
